package server

import (
	"fmt"
	"golang.org/x/net/context"
	"protobuf/model"
	pb "protobuf/trade"
)

type Server struct{}

func (c *Server) SetTrade(ctx context.Context, in *pb.TradeRequest) (*pb.Result, error) {
	r := &pb.Result{
		Status: pb.Result_SUCCESS,
	}
	if in.GetUid() == 0 {
		r.Status = pb.Result_FAIL
		r.Message = "invalid uid"
	}
	if in.GetPrice() <= 0 {
		r.Status = pb.Result_FAIL
		r.Message = "invalid price"
	}
	if in.GetTotalNum() <= 0 {
		r.Status = pb.Result_FAIL
		r.Message = "invalid total num"
	}
	if r.Status == pb.Result_FAIL {
		return r, nil
	}
	err := model.AddTrade(in)
	if err != nil {
		r.Status = pb.Result_FAIL
		r.Message = fmt.Sprintf("server insert error : %v", err)
		return r, nil
	}
	return &pb.Result{
		Message:      "success",
		Status:       pb.Result_SUCCESS,
		TradeRequest: in,
	}, nil
}

func (c *Server) GetUserTradeList(ctx context.Context, in *pb.TradeListRequest) (*pb.ListResult, error) {
	r := &pb.ListResult{}
	list, err := model.GetTradeList(in.GetUid(), in.GetIndex(), in.GetSize(), in.GetType(), in.GetStatus())
	if err != nil {
		r.Message = "server can`t find any thing"
		r.Status = pb.Result_FAIL
		r.Request = nil
		return r, err
	}
	for _, value := range list {
		tmp := &pb.TradeRequest{
			value.Id,
			value.Uid,
			value.Price,
			value.TotalNum,
			value.LeftNum,
			value.DealNum,
			value.Type,
			value.Status,
			value.Created,
			value.Updated,
		}
		r.Request = append(r.Request, tmp)
	}
	r.Status = pb.Result_SUCCESS
	return r, nil
}

func (c *Server) SetTradeCancel(ctx context.Context, in *pb.TradeCancelRequest) (*pb.CancelResult, error) {
	var cr = &pb.CancelResult{}
	if in.GetUid() == 0 {
		cr.Status = pb.Result_FAIL
		cr.Message = "invalid uid"
		return cr , nil
	}
	succ := model.CancelTrade(in.GetUid() ,in.GetId())
	if !succ {
		cr.Status = pb.Result_FAIL
		cr.Message = "cancel fail"
		return cr , nil
	}
	cr.Status = pb.Result_SUCCESS
	cr.Message = "cancel success"
	return cr , nil
}

func (c *Server) GetSystemTradeLog(ctx context.Context, in *pb.SystemTradeLogRequest) (*pb.TradeLogResult, error) {
	tlr := &pb.TradeLogResult{}
	rs , err := model.GetSystemLog(in.GetIndex() ,in.GetSize(),in.GetType())
	if err != nil {
		tlr.Status = pb.Result_FAIL
		tlr.Message = "request failed"
		return tlr , err
	}
	for _ , value := range rs {
		tmp := &pb.TradeLog{
			value.Id,
			value.Uid,
			value.PeerId,
			value.Price,
			value.Num,
			value.Amount,
			value.Type,
			value.Created,
			value.Updated,
		}
		tlr.Log = append(tlr.Log , tmp)
	}
	return tlr, nil
}
